package com.ukao.steward.ui.valetRunners.storage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;


import com.ukao.steward.R;
import com.ukao.steward.base.MvpActivity;
import com.ukao.steward.bean.ProductRelImgBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.pesenter.valetRunners.CameraPesenter;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.BitmapUtils;
import com.ukao.steward.util.CameraUtil;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.DensityUtils;
import com.ukao.steward.util.FileUtils;
import com.ukao.steward.util.ImageUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.util.UploadUtils;
import com.ukao.steward.view.valetRunners.CameraView;
import com.ukao.steward.widget.StateButton;
import com.ukao.steward.widget.StateImageView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static cn.jpush.android.api.JPushInterface.a.i;
import static com.ukao.steward.R.id.photo_count;
import static com.ukao.steward.R.id.picCnt;
import static com.ukao.steward.consts.Constant.ARG_PARAM1;
import static com.ukao.steward.consts.Constant.ARG_PARAM2;
import static com.ukao.steward.consts.Constant.ARG_PARAM3;


public class CameraActivity extends MvpActivity<CameraPesenter> implements CameraView, SurfaceHolder.Callback {

    @BindView(R.id.surfaceView)
    SurfaceView surfaceView;
    @BindView(R.id.photo)
    ImageView photo;
    @BindView(photo_count)
    TextView photoCount;
    @BindView(R.id.finish_btn)
    StateImageView finishBtn;
    @BindView(R.id.img_camera)
    StateImageView imgCamera;
    @BindView(R.id.back_btn)
    StateButton backBtn;
    private Camera mCamera;

    private SurfaceHolder mHolder;
    private int mCameraId = 0;
    private Context context;

    //屏幕宽高
    private int screenWidth;
    private int screenHeight;


    private int light_num = 0;

    private String photoPath;

    private SoundPool mSoundPool;
    private int outgoing;
    private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();
    private UploadUtils mUploadUtils;
    private String orderProId;
    private ArrayList<ProductRelImgBean> mPhotoData;
    private List uploadData = new ArrayList();/*上传图片集合*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
        setContentView(R.layout.activity_camera);
        ButterKnife.bind(this);
        context = this;
        initView();
        initData();
        initListener();
        takeCamerPhotoSoundPool();
    }

    @Override
    protected CameraPesenter createPresenter() {
        return new CameraPesenter(this);
    }

    protected void initView() {
        orderProId = getIntent().getStringExtra(ARG_PARAM1);
        mPhotoData =  getIntent().getParcelableArrayListExtra(ARG_PARAM2);

        if (!CheckUtils.isEmpty(mPhotoData)){
            ImageUtils.loadImage(_mActivity,mPhotoData.get(0).getCameraImg(),  photo);
            photoCount.setText(mPhotoData.size()+"");
        }else{
            mPhotoData=new ArrayList<>();
        }

        mHolder = surfaceView.getHolder();
        mHolder.addCallback(this);



    }

    @Override
    protected void initListener() {
        super.initListener();

    }


    ;

    public String getPhotoSavePath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/ukaoPOS/XKXPhoto/";
        } else {
            pathString = "/sdcard/ukaoPOS/XKXPhoto/";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }

    private void initData() {
        photoPath = getPhotoSavePath();
        screenWidth = DensityUtils.getScreenW()- DensityUtils.dip2px(20);
        screenHeight =DensityUtils.getScreenH() - DensityUtils.dip2px(120);

    }


    @SuppressLint("NewApi")
    public void takeCamerPhotoSoundPool() {
        //当前系统的SDK版本大于等于21(Android 5.0)时

        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频数量
            builder.setMaxStreams(2);
            //AudioAttributes是一个封装音频各种属性的方法
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适的属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            //加载一个AudioAttributes
            builder.setAudioAttributes(attrBuilder.build());
            mSoundPool = builder.build();
        }
        //当系统的SDK版本小于21时
        else {//设置最多可容纳2个音频流，音频的品质为5
            mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
        }
        soundID.put(1, mSoundPool.load(_mActivity, R.raw.success, 1));

    }




    @Override
    protected void onResume() {
        super.onResume();

        if (mCamera == null) {
            mCamera = getCamera(mCameraId);
            if (mCamera == null) {
                showError();
                return;
            }
            if (mHolder != null) {
                startPreview(mCamera, mHolder);
            }
        }
    }

    private void showError() {
        T.show(getResources().getString(R.string.unconnected_camera));
        finish();
    }



    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    /**
     * 获取Camera实例
     *
     * @return
     */
    private Camera getCamera(int id) {
        Camera camera = null;
        try {
            camera = Camera.open(id);
        } catch (Exception e) {

        }
        return camera;
    }

    /**
     * 预览相机
     */
    private void startPreview(Camera camera, SurfaceHolder holder) {
        try {
            setupCamera(camera);
            camera.setPreviewDisplay(holder);  /*那相机画面设置到holder上*/
            //亲测的一个方法 基本覆盖所有手机 将预览矫正
            CameraUtil.getInstance().setCameraDisplayOrientation(this, mCameraId, camera);
            camera.startPreview();

        } catch (IOException e) {

            e.printStackTrace();
        }
    }


    private void captrue() {

        mSoundPool.play(soundID.get(1), 1, 1, 0, 0, 1);
        mCamera.takePicture(null, null, new Camera.PictureCallback() {


            @Override
            public void onPictureTaken(byte[] data, Camera camera) {

                //将data 转换为位图 或者你也可以直接保存为文件使用 FileOutputStream
                //这里我相信大部分都有其他用处把 比如加个水印
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                Bitmap saveBitmap = CameraUtil.getInstance().setTakePicktrueOrientation(mCameraId, bitmap);

                saveBitmap = Bitmap.createScaledBitmap(saveBitmap, screenWidth, screenHeight, true);

                saveBitmap = Bitmap.createBitmap(saveBitmap, 0, 0, screenWidth, screenHeight);

                String img_path = photoPath + System.currentTimeMillis() + ".jpeg";
                BitmapUtils.saveJPGE_After(context, saveBitmap, img_path, 100);
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                }

                if (!saveBitmap.isRecycled()) {
                    saveBitmap.recycle();
                }

                compressWithLs(img_path);
                startPreview(mCamera, mHolder);

            }
        });
    }


    /**
     * 压缩图片 Listener 方式
     */
    private void compressWithLs(final String photos) {
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        mPhotoData.add(0, new ProductRelImgBean(file.getPath()));
                        ImageUtils.loadImage(_mActivity,mPhotoData.get(0).getCameraImg(),  photo);
                        photoCount.setText(mPhotoData.size()+"");

                    }

                    @Override
                    public void onError(Throwable e) {
                        mPhotoData.add(0, new ProductRelImgBean(photos));
                        ImageUtils.loadImage(_mActivity,mPhotoData.get(0).getCameraImg(),  photo);
                        photoCount.setText(mPhotoData.size()+"");

                    }
                }).launch();




    }


    public String getPath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/Ukaosteward/compressImage/";
        } else {
            pathString = "/sdcard/Ukaosteward/compressImage/";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }


    /**
     * 设置
     */
    private void setupCamera(Camera camera) {


        try {
            Camera.Parameters parameters = camera.getParameters();

            if (parameters.getSupportedFocusModes().contains(
                    Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            }
            //  camera.cancelAutoFocus();//只有加上了这一句，才会自动对焦。
            //这里第三个参数为最小尺寸 getPropPreviewSize方法会对从最小尺寸开始升序排列 取出所有支持尺寸的最小尺寸
            Camera.Size previewSize = CameraUtil.getInstance().getPropPictureSize(parameters.getSupportedPreviewSizes(), 800);
            L.i("previewSize.height=" + previewSize.height + "previewSize.width=" + previewSize.width);
            parameters.setPreviewSize(previewSize.width, previewSize.height);

            Camera.Size pictrueSize = CameraUtil.getInstance().getPropPictureSize(parameters.getSupportedPictureSizes(), 800);
            parameters.setPictureSize(pictrueSize.width, pictrueSize.height);
            camera.setParameters(parameters);

        } catch (Exception e) {

            showError();
        }


    }

    /**
     * 释放相机资源
     */
    private void releaseCamera() {

        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder != null) {
            startPreview(mCamera, holder);
        } else {
            showError();
        }

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (holder != null) {
            mCamera.stopPreview();
            startPreview(mCamera, holder);
        } else {
            showError();
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }

    @OnClick({R.id.finish_btn, R.id.img_camera, R.id.back_btn,R.id.photo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_btn:

                uploadData.clear();
                for (ProductRelImgBean mImgBean : mPhotoData) {
                    if (CheckUtils.isHttp(mImgBean.getCameraImg())) {
                        uploadData.add(mImgBean.getCameraImg());
                    }

                }
                if (CheckUtils.isEmpty(uploadData)) {
                    finish();
                    return;
                }
                mvpPresenter.qiniutoken();
                break;
            case R.id.img_camera:
                if (mPhotoData.size()==10){
                    T.show(getResources().getString(R.string.maximum_ten));
                    return;
                }
                if (mHolder != null && mCamera != null) {
                    captrue();
                }

                break;
            case  R.id.photo :
                if (CheckUtils.isEmpty(mPhotoData))return;
                ActivityUtils.JumpPhotoListActivity(_mActivity,mPhotoData.size()-1,mPhotoData);
                break;


            case R.id.back_btn:
                finish();
                break;

        }
    }

    /**
     * @param token 七牛token
     */
    @Override
    public void loadQiLitoken(String token) {

        if (this.mUploadUtils == null) {
            this.mUploadUtils = new UploadUtils();
        }
        mUploadUtils.startImageUpload(this, token, uploadData, mOnOSSFileUpload);


    }


    private UploadUtils.OnOSSFileUploadFinish mOnOSSFileUpload = new UploadUtils.OnOSSFileUploadFinish() {
        @Override
        public void OnUploadFinish(String image, String video, String videoImage) {
            L.i("image=" + image);
            mvpPresenter.addphotoOrder(orderProId, image);

        }
    };



    @Override
    public void addphotoSucceed() {
        FileUtils.deleteAllInDir(getPhotoSavePath());
        FileUtils.deleteAllInDir(getPath());
        setPhotoResult(mPhotoData.size());
    }

    private void setPhotoResult(int photoCount) {
        Intent mIntent=new Intent();
        mIntent.putExtra(ARG_PARAM1,photoCount);
        setResult(RESULT_OK,mIntent);
        finish();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSoundPool.release();
    }


}
